// productPackage/pages/outStock/outStock.js

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    path: app.globalData.path,
    showCus: false, // 选择客户弹窗
    showProduct: false, // 选择开单商品弹窗
    showSuccess: false, // 开单成功弹窗
    cusList: [], //我的客户列表
    selectCus: '', // 所选择的客户

    outNum: '', //订单号


    oldProductList: [], // 原始全部商品列表
    productList: [], //全部商品列表
    selectProductList: [], //选中的商品列表

    productNum: 0, //所选商品件数
    productTotal: 0, //所选商品总钱数


    faPiao: '', //发票信息
    showPiao: false, //是否显示发票
    actions: [{
        name: '普票',
      },
      {
        name: '专票',
      },
      {
        name: '无票',
      },
    ],
    customerId: '', //客户id
    note: '', //备注信息
  },

  // 现结开单
  kaidanHandle() {


    if (this.data.selectCus == '') {
      wx.showToast({
        title: '请选择客户',
        icon: 'none'
      })
      return
    }

    if (this.data.selectProductList.length == 0) {
      wx.showToast({
        title: '请选择开单商品',
        icon: 'none'
      })
      return
    }
    if (this.data.faPiao == '') {
      wx.showToast({
        title: '请选择发票信息',
        icon: 'none'
      })
      return
    }

    console.log(this.data.selectCus);
    console.log(this.data.selectProductList);
    console.log(this.data.faPiao);

    var url = app.globalData.url + "outStock/addOutStock",
      that = this;
    // wx.showLoading({
    //   title: '',
    // })
    app.wxRequestJson(url, {
        userId: app.globalData.userId,
        customerId: that.data.selectCus.customerId,
        productNum: that.data.productNum,
        totalMoney: that.data.productTotal.toFixed(2),
        invoice: that.data.faPiao,
        outNote: that.data.note,
        companyId: app.globalData.companyId,
        itemList: that.data.selectProductList,
      }, res => {
        console.log(res);
        if (res.flag) {
          //开单成功的页面
          wx.showModal({
            title: '提示',
            content: '开单成功',
            cancelText: '继续开单',
            confirmText: '立即查看',
            complete: (res) => {
              if (res.cancel) {
                that.setData({
                  selectProductList: [],
                  productNum: 0,
                  productTotal: 0,
                  faPiao: '',
                  note: '',
                })
                that.getProduct()
              }
              if (res.confirm) {
                // 立即查看
                wx.redirectTo({
                  url: '/customerPackage/pages/customerDetail/customerDetail?customer=' + JSON.stringify(that.data.selectCus),
                })
              }
            }
          })



        }

      },
      err => {
        console.log(err);
      })

  },

  inputHandle(e) {
    var str = e.currentTarget.dataset.flag
    var val = e.detail.value
    console.log(e);
    this.setData({
      [str]: val
    })
    console.log(this.data.note);
  },

  // 删除选中的商品
  delProduct(e) {
    var index = e.currentTarget.dataset.index,
      list = this.data.selectProductList,
      productlist = this.data.productList,
      productNum = 0,
      productTotal = 0,
      that = this,
      product = list[index];

    wx.showModal({
      title: '提示',
      content: '是否删除该商品',
      complete: (res) => {
        if (res.confirm) {
          list.splice(index, 1)
          productlist.forEach(ele => {
            if (ele.stockId == product.stockId) {
              ele.num = 0
            }
          })

          list.forEach(ele => {
            productNum += ele.num
            productTotal += ele.num * ele.salePrice;
            ele.productPrice = ele.salePrice;
          })
          that.setData({
            selectProductList: list,
            productlist,
            productNum,
            productTotal
          })
          console.log(productlist);
          console.log(this.data.productlist);
        }
      }
    })
  },

  proNumInput(e) {
    console.log(e);
    var index = e.currentTarget.dataset.index,
      list = this.data.productList,
      productNum = 0,
      productTotal = 0,
      val = e.detail.value;
    list[index].num = val

    if (list[index].num > list[index].productNum) {
      wx.showToast({
        title: '商品数量不得大于库存',
        icon: 'none'
      })
      list[index].num = list[index].productNum
    } else if (val < 0) {
      wx.showToast({
        title: '商品数量不得小于0',
        icon: 'none'
      })
      list[index].num = 0
    }

    list.forEach(ele => {
      if (ele.num != 0) {
        productNum += Number(ele.num)
        productTotal += Number(ele.num) * ele.salePrice
      }
    })

    this.setData({
      productList: list,
      productNum,
      productTotal,
    })


  },
  onChange(e) {
    console.log(e);
    this.setData({
      activeNames: e.detail,
    });
  },


  numHandle(e) {
    var flag = e.currentTarget.dataset.flag,
      index = e.currentTarget.dataset.index,
      list = this.data.productList,
      selectProductList = [],
      productNum = 0,
      productTotal = 0;
    console.log(list[index]);
    if (flag == 'add') {
      list[index].num++
    } else {
      list[index].num--
    }
    if (list[index].num > list[index].productNum) {
      wx.showToast({
        title: '商品数量不得大于库存',
        icon: 'none'
      })
      list[index].num = list[index].productNum
    }
    list.forEach(ele => {
      if (ele.num != 0) {
        productNum += ele.num
        productTotal += ele.num * ele.salePrice;
        ele.productPrice = ele.salePrice;
      }
    })

    this.setData({
      productList: list,
      productNum,
      productTotal,
    })




  },

  // 选择商品确认
  subProduct() {
    var list = this.data.productList,
      selectProductList = [];
    list.forEach(ele => {
      if (ele.num != 0) {
        ele.productNum = ele.num;
        ele.productPrice = ele.salePrice;
        ele.itemUnit = ele.productUnit;
        selectProductList.push(ele)
      }
    })
    this.setData({
      selectProductList,
      showProduct: false
    })
    console.log(selectProductList);
  },

  // 显示弹窗
  showHandle(e) {
    var flag = e.currentTarget.dataset.flag;
    if (flag == 'cus') {
      this.setData({
        showCus: true
      })
    } else if (flag == 'product') {
      var productList = this.data.productList,
        selectProductList = this.data.selectProductList;

      if (selectProductList.length != 0) {
        productList.forEach(ele => {
          selectProductList.forEach(item => {
            if (ele.stockId == item.stockId) {
              ele.num = item.num
            }
          })
        })
      }
      this.setData({
        showProduct: true,
        productList
      })
    } else if (flag == 'faPiao') {
      this.setData({
        showPiao: true
      })
    }
  },

  // 关闭弹窗
  onClose(e) {
    var flag = e.currentTarget.dataset.flag;
    if (flag == 'cus') {
      this.setData({
        showCus: false
      })
    } else if (flag == 'product') {
      this.setData({
        showProduct: false
      })
    } else if (flag == 'faPiao') {
      this.setData({
        showPiao: false
      })
    } else if (flag == 'success') {
      this.setData({
        showSuccess: false
      })
    }
  },
  // 选择发票
  onSelect(e) {
    this.setData({
      faPiao: e.detail.name,
      showPiao: false
    })


  },


  checkDetail() {

    var outId = ''
    // return
    wx.redirectTo({
      url: '/customerPackage/pages/orderDetail/orderDetail?outId=' + outId,
    })
  },

  // 选择客户
  onSelectChange(e) {
    console.log(e);
    var index = e.currentTarget.dataset.index,
      list = this.data.cusList,
      selectCus = '';

    list.forEach((ele, eIndex) => {
      if (eIndex == index) {
        ele.isSelect = !ele.isSelect
        if (ele.isSelect) {
          selectCus = ele
        }
      } else {
        ele.isSelect = false
      }
    })

    this.setData({
      cusList: list,
      selectCus,
      showCus: selectCus == ''
    })

    console.log(selectCus);
  },


  getCusList() {
    var url = app.globalData.url + "customer/lisUserCustomer",
      that = this,
      selectCus = '',
      customerId = this.data.customerId;
    wx.showLoading({
      title: '',
    })
    app.wxRequest(url, {
        userId: app.globalData.userId,
      }, res => {
        console.log(res);
        if (res.flag) {
          var result = res.data
          wx.hideLoading()
          console.log(res);
          result.forEach(item => {
            item.isSelect = false
            if (item.customerId == customerId) {
              console.log(item);
              item.isSelect = true
              selectCus = item
            }

          })
          that.setData({
            cusList: result,
            selectCus
          })
        }
      },
      err => {
        console.log(err);
      })
  },



  getProduct() {
    var url = app.globalData.url + "product/listAllProduct",
      that = this,
      productList = [];
    wx.showLoading({
      title: '',
    })
    app.wxRequest(url, {
        companyId: app.globalData.companyId
      }, res => {
        console.log(res);
        if (res.flag) {
          wx.hideLoading()

          console.log(res);
          productList = res.data;
          // productList = productList.filter(
          //   (item, index, origin) =>
          //   index ===
          //   origin.findIndex((itemInner) => {
          //     return itemInner.productId === item.productId;
          //   })
          // );

          productList.forEach(ele => {
            ele.num = 0
          })

          that.setData({
            productList,
            oldProductList: res.data
          })
          console.log(productList);
        }
      },
      err => {
        console.log(err);
      })


  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    if (options) {
      this.setData({
        customerId: options.cusId
      })
    }

    this.getCusList()
    this.getProduct()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})